package config

import (
	"embed"
	"encoding/json"
	"flag"
	"fmt"
	"gorm.io/gorm"
	"log"
)

////go:embed "/assert"
//var AssertFile embed.FS

//func init() {
//	Setup()
//}

// Config 配置对象
type Config struct {
	Database *map[string]Database `json:"database"`
}

// GlobalConfigSetting 配置实例
var GlobalConfigSetting = &Config{}
var strFlag = flag.String("c", "config_dev.json", "config")

// OpenDB 配置
func OpenDB(AssertFile embed.FS) {
	flag.Parse()

	configFile := *strFlag
	if configFile == "" {
		panic("请加入-c 参数")
	}
	filePtr, err := AssertFile.Open("config/config.json") //config的文件目录
	if err != nil {
		fmt.Println("读取配置文件失败：", err.Error())
		return
	} else {
		log.Printf("读取配置文件成功：%s", configFile)
	}
	defer filePtr.Close()
	// 创建json解码器
	decoder := json.NewDecoder(filePtr)
	err = decoder.Decode(GlobalConfigSetting)
	Connects = GlobalConfigSetting.Database
}

// Database 数据库配置对象
type Database struct {
	ConnectType string   `json:"connectType"`
	Type        string   `json:"type"`
	User        string   `json:"user"`
	Password    string   `json:"password"`
	Host        string   `json:"host"`
	Port        string   `json:"port"`
	Name        string   `json:"name"`
	TablePrefix string   `json:"table_prefix"`
	Db          *gorm.DB `json:"db"`
}

// Connects 数据库链接对象池
var Connects = &map[string]Database{}
